﻿<?php defined('SYSPATH') or die('No direct script access.');
require ('application/classes/dao/base.php');
require ('application/classes/dao/ValidateCode.php');
require ('application/classes/dao/Captcha.php');
require ('application/classes/dao/email.class.php');
require "pay/lib/WxPay.Api.php";
require ("application/classes/dao/WxPay.NativePay.php");

class Controller_user extends Controller {


	public function action_forget(){
		echo View::factory('web/forget');
	}


	public function action_index(){
		checkUserSession();
		echo View::factory('web/personal');
	}
	public  function  action_forgetUser(){
		$parm = post($this->request);
		$result = null;
		try{
			if(!isset($parm['phone']) ||($parm['phone'])==""){
				echo "手机不能为空";
				exit;
			}
			if(!isset($parm['code']) ||($parm['code'])==""){
				echo "验证码不能为空";
				exit;
			}
			if(!isset($parm['password']) ||($parm['password'])==""){
				echo "密码不能为空";
				exit;
			}
			Kohana::$log->add(Log::INFO,$parm['phone'].'找回密码');
			$msg = rpcCall('user.modfiyPassword',$parm);

		}catch (Exception $e){

			Kohana::$log->add(Log::ERROR,$parm['phone'].'发生异常:'.$e->getMessage());
			$msg = "找回密码失败";
		}finally{
			if($msg ==""){
				Kohana::$log->add(Log::INFO,$parm['phone'].'找回密码成功');
				echo "<script>window.location.href='".Url::base()."'</script>";
			}else{
				echo View::factory('web/forget')->set('msg',$msg);
			}
		}
	}

	public function action_modfiyPersonal(){
		$result = null;
		$parm = post($this->request);
		try{

			$user = getUserSession();

			if($user == null){
				$result['data'] = '未登录';
				$result['msg'] = false;
				return ;
			}



			if(!isset($parm['email']) ||($parm['email'])==""){
				$result['data'] = "邮箱不能为空";
				$result['msg'] = false;
				return;
			}
			if(!isset($parm['phone']) ||($parm['phone'])==""){
				$result['msg'] = false;
				$result['data'] = '手机号不能为空';
				return;
			}
			if(!isset($parm['sex'])){
				$parm['sex'] = '';
			}
			if(!isset($parm['age'])){
				$parm['age'] = '';
			}

			if($parm['email']==$user['email']){
				$result['data'] = "邮箱已经注册";
				$result['msg'] = false;
				return;
			}
			if($parm['phone']==$user['phone']){
				$result['data'] = "手机号已经注册";
				$result['msg'] = false;
				return;
			}
			$parm['id'] = $user['id'];
			$result = rpcCall('user.modifyUser',$parm);

		}catch (Exception $e){
			$result['data']='检查用户名失败请刷新再试';
			$result['code'] = -1;
			$result['error'] =$e->getMessage();
		}finally{
			echo json_encode($result);
		}
	}
	public function action_corpImg(){
		try{
			$result = null;
			$user = getUserSession();

			if($user == null){
				$result['msg'] = -1;
				return ;
			}
			$old = '';
			if(isset($user['img'])){
				$old = $user['img'];
			}
			$parm = post($this->request);
			$src ="temp/". $parm['file'];
			$x = $parm['x1'];
			$y = $parm['y1'];
			$width = $parm['w'];
			$height = $parm['h'];
			Image::factory($src)->crop($width,$height,$x,$y)->save($src);
			try{
				rename($src,"uploads/". $parm['file']);
			}catch (Exception $e){}
			$parm['img'] =  $parm['file'];
			$parm['id'] = $user['id'];
			rpcCall('user.updateUserImg',$parm);
			$user['img'] = $parm['img'];
			setUserSession('user',$user);
			$result['msg'] = 1;
			try{
				unlink('uploads/'.$old);
			}catch (Exception $e){}

		}catch (Exception $e){

			$result['error'] =$e->getMessage();
			$result['msg'] = -2;
		}
		echo json_encode($result);
	}


	public function action_sendForgetPassword(){
		$parm = get($this->request);
		$result = null;
		try{
			if(!isset($parm['phone']) ||($parm['phone'])==""){
				echo "手机不能为空";
				exit;
			}
			$checkcode =  rand(100000, 999999);
			$parm['use'] = "未使用";
			$parm['model'] = '找回密码';
			$parm['ValidateCode']=$checkcode;
			$parm['action'] = 'forget';
			$getresult = rpcCall('checkcode.sendCode',$parm);

			if($getresult['flag']){
				$content = '欢迎来到开源商城,您的验证码:';
//			$result['msg'] = sendSMS($parm['phone'],$content.$checkcode);
				$result['msg'] = true;
				return ;
			}else{
				$result['data'] = $getresult['data'];
				$result['msg'] = false;
			}


		}catch (Exception $e){
			$result['msg']='检查用户名失败请刷新再试';
			$result['code'] = -1;
			$result['error'] =$e->getMessage();
		}finally{
			echo json_encode($result);
		}
	}
	public function action_sendBindEmail(){
		$parm = get($this->request);
		$result = null;
		try{
			$result = null;
			$user = getUserSession();

			if($user == null){
				$result['data'] = '未登录';
				$result['msg'] = false;
				return ;
			}
			if(!isset($parm['email']) ||($parm['email'])==""){
						$result['data'] = "邮箱不能为空";
						$result['msg'] = false;
					return;
			}
			$pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
			if ( !preg_match( $pattern, $parm['email'] ) )
			{
				echo "邮箱不合法";
				exit;
			}
			if($user['email'] == $parm['email']){
				$result['data'] = '邮箱已经绑定';
				$result['msg'] = false;
				return ;
			}

			$checkcode =  rand(100000, 999999);
			$parm['use'] = "未使用";
			$parm['model'] = '绑定邮箱';
			$parm['ValidateCode']=$checkcode;
			$parm['action'] = 'forget';
			$getresult = rpcCall('checkcode.sendCodeEmail',$parm);

			if($getresult['flag']){
// 				$mail = new MySendMail();
// 				$mail->setServer("smtp.qq.com", "453111208@qq.com", "nn201314nn", 465, false); //到服务器的SSL连接
// // 如果不需要到服务器的SSL连接，这样设置服务器：$mail->setServer("smtp.126.com", "XXX@126.com", "XXX");
// 				$mail->setFrom("453111208@qq.com");
// 				$mail->setReceiver($parm['email']);
// 				$mail->setReceiver($parm['email']);
//
// 				$mail->setMail("绑定邮箱", '欢迎使用openshop,您的验证码:'.$checkcode);
// 				$mail->sendMail();
				$result['msg'] = true;
				return ;
			}else{
				$result['data'] = $getresult['data'];
				$result['msg'] = false;
			}


		}catch (Exception $e){
			$result['data']='检查用户名失败请刷新再试';
			$result['code'] = -1;
			$result['error'] =$e->getMessage();
		}finally{
			echo json_encode($result);
		}
	}

		public function action_sendBindPhone(){
		$parm = get($this->request);
		$result = null;
		try{
			$result = null;
			$user = getUserSession();

			if($user == null){
				$result['msg'] = false;
				$result['data'] = '未登录';
				return ;
			}
			if(!isset($parm['phone']) ||($parm['phone'])==""){
				$result['msg'] = false;
				$result['data'] = '手机号不能为空';
				exit;
			}
			
			if($user['phone'] == $parm['phone']){
				$result['msg'] = false;
				$result['data'] = '手机号已经绑定';
				return ;
			}

			$checkcode =  rand(100000, 999999);
			$parm['use'] = "未使用";
			$parm['model'] = '绑定手机号';
			$parm['ValidateCode']=$checkcode;
			$parm['action'] = 'forget';
			$getresult = rpcCall('checkcode.sendBindPhone',$parm);

			if($getresult['flag']){
				$content = '欢迎来到开源商城,您的验证码:';
				$result['msg'] = true;
				return ;
			}else{
				$result['data'] = $getresult['data'];
				$result['msg'] = false;
			}


		}catch (Exception $e){
			$result['data']='检查用户名失败请刷新再试';
			$result['code'] = -1;
			$result['error'] =$e->getMessage();
		}finally{
			echo json_encode($result);
		}
	}

	public function action_address(){
		$result = checkUserSessionOrJumpLogin();
		$parm['userId'] = $result['id'];
		$result = rpcCall('china.getProvince',null);
		$address = rpcCall('userAddress.getByUserId',$parm);
		echo View::factory('web/userAddress')->set('list',$result)->set("address",$address);
	}
	public function action_pay(){
		$result = checkUserSessionOrJumpLogin();
		$parm['userId']=$result['id'];
		$result = rpcCall('userassert.getByUserId',$parm);
		$assert = 0 ;
		if(count($result)!= 0 ){
			$assert = $result[0]['assert'];
		}
        echo View::factory('web/pay')->set('money',$assert);
    }

   	public function action_create(){

   		$notify = new NativePay();
		$url1 = $notify->GetPrePayUrl("123456789");

		//模式二
		/**
		 * 流程：
		 * 1、调用统一下单，取得code_url，生成二维码
		 * 2、用户扫描二维码，进行支付
		 * 3、支付完成之后，微信服务器会通知支付成功
		 * 4、在支付成功通知中需要查单确认是否真正支付成功（见：notify.php）
		 */

		$parm = get($this->request);
		$result = null;
		checkUserSession();
		$user = getUserSession();

		date_default_timezone_set('PRC');
		$parm['Out_trade_no'] = WxPayConfig::MCHID.date("YmdHis");
		$parm['money'] = 1;
		$parm['status'] = '未充值';
		$parm['model'] = '充值';
		$parm['come'] = '微信';
		$parm['orderId'] = null;
		$parm['userId']=$user['id'];
		$result = rpcCall('recharge.insert',$parm);
		print_r($result);

		if($result['msg']== true){
			$input = new WxPayUnifiedOrder();
			$input->SetBody("欢迎openshop电商充值");
			$input->SetAttach("充值");

			$input->SetOut_trade_no($parm['Out_trade_no']);
			$input->SetTotal_fee($parm['money'] );
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 1000));
			$input->SetGoods_tag("充值");

			require_once ('application/classes/config/sysconfig.php');
			$sysconfig = new sysconfig();

			$input->SetNotify_url($sysconfig->weixinurl."/kohana/pay/example/notify.php");
			$input->SetTrade_type("NATIVE");
			$input->SetProduct_id("123456789");
			echo $sysconfig->weixinurl."/kohana/pay/example/notify.php";
			print_r($input);
			$result = $notify->GetPayUrl($input);
			$url2 = $result["code_url"];
		}else{
			echo "<script>window.location.href='".Url::base()."index.php/user/pay?message=1'</script>";

			return false;
		}

        echo View::factory('web/payUrl')->set("url",$url2);
    }

    public function action_notify(){
    	$parm = get($this->request);
		Kohana::$log->add(Log::INFO,'111'.json_encode($parm));
		$parm = post($this->request);
		Kohana::$log->add(Log::INFO,''.json_encode($parm));
		echo true;
		die;
    }

    public function action_createErweima(){
    	error_reporting(E_ERROR);

    	$parm = get($this->request);
		require_once 'pay/example/phpqrcode/phpqrcode.php';
		$url = urldecode($parm["data"]);
		QRcode::png($url);
    }
	public function action_updateTradeNo(){
		$parm = get($this->request);
		rpcCall('recharge.update',$parm);
	}

	public function action_userMessage(){

		$result = checkUserSessionOrJumpLogin();

		$parm = get($this->request);
		
		if(!isset($parm['page']) ){
			$parm['page'] = 1;
		}
		$parm['userId']=$result['id'];
		$result =rpcCall("message.getListByUserId",$parm);

		echo View::factory('web/userMessage')->set("list",$result)->set("page",$parm['page']);
	}

	public function action_deteleMessage(){
		$result = checkUserSessionOrJumpLogin();
		$msg =null;
		$parm = post($this->request);

		try{
			if(!isset($parm['id']) ||$parm['id'] == ""){
				$msg['data'] = '请选择删除对象';
				return ;
			}
			rpcCall('message.deleteBatch',$parm);
			$msg['data'] = '删除成功';
		}catch(Exception $e){
			$msg['error']= $e->getMessage();
			$msg['data'] = '删除失败';

		}finally{
			echo json_encode($msg);
		}
		

	}

	public function action_detailMessage(){

		checkUserSession();

		$parm = get($this->request);
		
		$entity = rpcCall("message.detail",$parm);
		echo View::factory('web/detailMessage')->set("entity",$entity);
	}

	public function action_userSign(){

		$result = checkUserSessionOrJumpLogin();

		date_default_timezone_set('PRC');
		$begin = date('Y-m-01', strtotime(date("Y-m-d")));;
		$parm['userId'] = $result['id'];
		$parm['begin'] = $begin;
		$parm['end']= date('Y-m-d', strtotime($begin." +1 month -1 day"));

		$result = rpcCall('usersign.getListByMonth',$parm);
		$list =  array();
		foreach($result as $key=>$value){

			$list[$key] =intval(date('d', strtotime($value['signDate'])));
		}


		echo View::factory('web/userSign')->set('list',json_encode($list))->set('size',count($list));
	}
	public function action_sign(){
		$result = checkUserSessionOrJumpLogin();
		$parm['userId'] = $result['id'];
		date_default_timezone_set('PRC');
		$begin = date('Y-m-d', time());;
		$parm['signDate']=$begin;
		$result = rpcCall('usersign.sign',$parm);
	}

	public function action_insertAddress(){
		$parm = post($this->request);
		$result = null;
		try {
			$result = null;
			$user = getUserSession();

			if ($user == null) {
				$result['msg'] = false;
				$result['data'] = '未登录';
				return;
			}
			$parm['userId']=$user['id'];
			if(!isset($parm['provinceId']) ||($parm['provinceId'])==""){
				$result['data'] = "请选择省份不能为空";
				$result['msg'] = false;
				return;
			}
			if(!isset($parm['cityId']) ||($parm['cityId'])==""){
				$result['data'] = "请选择城市不能为空";
				$result['msg'] = false;
				return;
			}
			if(!isset($parm['username']) ||($parm['username'])==""){
				$result['data'] = "收货人姓名不能为空";
				$result['msg'] = false;
				return;
			}
			if(!isset($parm['phone']) ||($parm['phone'])==""){
				$result['data'] = "手机号不能为空";
				$result['msg'] = false;
				return;
			}
			rpcCall('userAddress.insert',$parm);
			$result['data'] = "地址添加成功";
			$result['msg'] = true;
		}catch (Exception $e){
			$result['msg'] = false;
			$result['error']=$e->getMessage();
			$result['data'] = '系统异常，重新尝试';
		}finally{
			echo json_encode($result);
		}
	}

	public function action_deleteAddress(){
		$parm = get($this->request);
		checkUserSession();
		rpcCall('userAddress.deleteById',$parm);
		echo "<script>window.location.href='".Url::base()."index.php/user/address'</script>";
	}
}
